﻿//-------------------------------------------------------------------------------------------------
// <copyright file="Table.cs" company="Oliver Hallam">
// Copyright (c) 2008 Oliver Hallam
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// </copyright>
//-------------------------------------------------------------------------------------------------

namespace DBLite
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics.CodeAnalysis;
    using System.Diagnostics.Contracts;
    using Contracts;

    /// <summary>
    /// A database table.
    /// </summary>
    public class Table : ITable
    {
        #region Fields

        /// <summary>
        /// The rows making up the table.  Each row is made up of an array of strings.
        /// </summary>
        private readonly List<string[]> rows;

        /// <summary>
        /// The columns that make up this table.
        /// </summary>
        private readonly Columns columns;

        #endregion

        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="Table"/> class.
        /// </summary>
        /// <param name="columns">The columns that make up the table.</param>
        /// <exception cref="ArgumentNullException"><paramref name="columns"/> is <see langword="null" /></exception>
        public Table(Columns columns)
        {
            Ensure.ArgumentNotNull(columns, "columns");

            this.columns = columns;
            this.rows = new List<string[]>();
        }

        #endregion

        #region ITable Members

        /// <summary>
        /// Gets the columns that make up this table.
        /// </summary>
        /// <value>The columns that make up this table.</value>
        public Columns Columns
        {
            get
            {
                return this.columns;
            }
        }

        /// <summary>
        /// Adds a row to the table.
        /// </summary>
        /// <returns>The ID of the added row.</returns>
        public int CreateRow()
        {
            int id = this.rows.Count;
            this.rows.Add(this.NewRow());
            return id;
        }

        /// <summary>
        /// Deletes a row from the table.
        /// </summary>
        /// <param name="rowId">The ID of the row to be deleted.</param>
        public void DeleteRow(int rowId)
        {
            if (rowId < 0 || rowId >= this.rows.Count)
            {
                throw new ArgumentOutOfRangeException("rowId", ExceptionResources.InvalidRowId(rowId));
            }

            this.rows[rowId] = null;
        }

        /*
        /// <summary>
        /// Gets the value of a cell in the table
        /// </summary>
        /// <param name="rowId">The ID of the row to retrieve.</param>
        /// <param name="columnId">The ID of the column to retrieve.</param>
        /// <returns>The value of the cell</returns>
        /// <remarks>No validity checking is performed on row and column IDs.</remarks>
        [NotNull]
        internal string FastGetCell(int rowId, int columnId)
        {
            Assert.ArgumentInRange(rowId, rows.Count, "rowId");
            Assert.ArgumentInRange(columnId, Columns.Count, "columnId");
            
            var row = rows[rowId];

            Assert.IsNotNull(row, "row");

            return row[columnId];
        }
        */

        /// <summary>
        /// Gets the value of a cell in the table.
        /// </summary>
        /// <param name="rowId">The ID of the row to retrieve.</param>
        /// <param name="columnId">The ID of the column to retrieve.</param>
        /// <returns>The value of the cell</returns>
        /// <exception cref="ArgumentOutOfRangeException">
        /// <paramref name="rowId"/> refers to a row that is not in the table, or <paramref name="columnId"/> is not
        /// a valid column ID for this table.
        /// </exception>
        public string GetCell(int rowId, int columnId)
        {
            if (rowId < 0 || rowId >= this.rows.Count)
            {
                throw new ArgumentOutOfRangeException("rowId", ExceptionResources.InvalidRowId(rowId));
            }

            if (columnId < 0 || columnId >= this.columns.Count)
            {
                throw new ArgumentOutOfRangeException("columnId", ExceptionResources.InvalidColumnId(columnId));
            }

            string[] row = this.rows[rowId];
            if (row == null)
            {
                throw new ArgumentOutOfRangeException("rowId", ExceptionResources.InvalidRowId(rowId));
            }

            Contract.Assume(row.Length == this.columns.Count);

            return row[columnId];
        }

        /// <summary>
        /// Returns a value indicating whether a row exists in the table with the given ID.
        /// </summary>
        /// <param name="rowId">The row ID.</param>
        /// <returns>
        /// <see langword="true" /> if a row with ID <paramref name="rowId"/> exists; 
        /// <see langword="false" /> otherwise.
        /// </returns>
        public bool RowExists(int rowId)
        {
            return rowId >= 0 && rowId < this.rows.Count && this.rows[rowId] != null;
        }

        /// <summary>
        /// Sets the value of a cell in the table.
        /// </summary>
        /// <param name="rowId">The ID of the row to set.</param>
        /// <param name="columnId">The ID of the column to set.</param>
        /// <param name="value">The value to set the cell to.</param>
        /// <exception cref="ArgumentOutOfRangeException">
        /// <paramref name="rowId"/> refers to a row that is not in the table, or <paramref name="columnId"/> is not
        /// a valid column ID for this table.
        /// </exception>
        public void SetCell(int rowId, int columnId, string value)
        {
            if (columnId < 0 || columnId >= this.columns.Count)
            {
                throw new ArgumentOutOfRangeException("columnId", ExceptionResources.InvalidColumnId(columnId));
            }

            if (rowId < 0 || rowId >= this.rows.Count)
            {
                throw new ArgumentOutOfRangeException("rowId", ExceptionResources.InvalidRowId(rowId));
            }

            string[] row = this.rows[rowId];
            if (row == null)
            {
                throw new ArgumentOutOfRangeException("rowId", ExceptionResources.InvalidRowId(rowId));
            }

            Contract.Assume(row.Length == this.columns.Count);

            row[columnId] = value;
        }

        #endregion

        #region Methods

        /// <summary>
        /// Object Invariants
        /// </summary>
        [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "Code contract")]
        [ContractInvariantMethod]
        protected void ObjectInvariants()
        {
            Contract.Invariant(this.columns != null);
            Contract.Invariant(this.rows != null);
            ////Contract.Invariant(Contract.ForAll(this.rows, row => row == null || row.Length == this.columns.Count));
        }

        /// <summary>
        /// Creates a new row to be used in the table.
        /// </summary>
        /// <returns>A new row to be used in the table.</returns>
        private string[] NewRow()
        {
            return new string[this.columns.Count];
        }

        #endregion
    }
}